<template>
    <div class="snow-page">
        <div class="snow-inner-page">
            <a-form :model="formData.form" :label-col-props="{ span: 5 }" :wrapper-col-props="{ span: 18 }"
                ref="formRef">
                <a-row :gutter="16">
                    <a-col :span="6">
                        <a-form-item field="name" label="账号">
                            <a-input v-model="formData.form.name" placeholder="账号" allow-clear />
                        </a-form-item>

                    </a-col>

                    <a-col :span="6">
                        <a-space>
                            <a-button type="primary" @click="onSearch">
                                <template #icon>
                                    <icon-search />
                                </template>
                                <template #default>查询</template>
                            </a-button>
                            <a-button @click="onReset">
                                <template #icon>
                                    <icon-refresh />
                                </template>
                                <template #default>重置</template>
                            </a-button>
                            <!-- <a-button type="primary" @click="onAdd">
                                <template #icon>
                                    <icon-PlusOutlined />
                                </template>
                                <template #default>新增</template>
                            </a-button> -->
                        </a-space>
                    </a-col>
                </a-row>
            </a-form>
            <a-table :data="tableData" row-key="id" size="small" bordered :pagination="false">
                <template #columns>

                    <a-table-column title="名称">
                        <template #cell="{ record }">
                            {{ record.name }}

                        </template>
                    </a-table-column>
                    <a-table-column title="密码">
                        <template #cell="{ record }">
                            {{ record.password }}
                        </template>
                    </a-table-column>
                    <a-table-column title="手机号">
                        <template #cell="{ record }">
                            {{ record.phone }}
                        </template>
                    </a-table-column>
                    <a-table-column title="邮箱">
                        <template #cell="{ record }">
                            {{ record.email }}
                        </template>
                    </a-table-column>
                    <a-table-column title="角色">
                        <template #cell="{ record }">
                            {{ record.data.type }}

                        </template>
                    </a-table-column>
                    <a-table-column title="状态">
                        <template #cell="{ record }">
                            {{ record.data.status }}

                        </template>
                    </a-table-column>
                    <a-table-column title="操作" align="center" fixed="right">
                        <template #cell="{ record }">
                            <a-space>
                                <a-button size="mini" type="primary" @click="onEdit(record)">修改</a-button>
                                <a-button size="mini" type="primary" status="danger"
                                    @click="onDelete2(record)">删除</a-button>
                            </a-space>
                        </template>
                    </a-table-column>
                </template>
            </a-table>
            <a-pagination :total="total" style="margin-top:10px;" @change="changePage" />
        </div>



        <a-modal v-model:visible="visible" :footer="false" width="60%">
            <template #title>
                用户{{ form.name }}关联通道
            </template>
            <div>
                <!-- <a-form ref="formRef" :model="form" @submit="handleSubmit" layout='inline'>
                    <a-form-item field="name" label="账号" :rules="[{ required: true, message: '账号不能为空' }]">
                        <a-input v-model="form.name" placeholder="请输入账号" />
                    </a-form-item>
                    <a-form-item field="type" label="用户类型" :rules="[{ required: true, message: '用户类型不能为空' }]">
                        <a-select v-model="form.type" placeholder="用户类型" allow-clear>
                            <a-option value="7">普通用户</a-option>
                            <a-option value="8">管理员</a-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item>
                        <a-space>
                            <a-button html-type="submit">提交</a-button>
                            <a-button @click="$refs.formRef.resetFields()">重置</a-button>
                        </a-space>
                    </a-form-item>
                </a-form> -->

                <!-- <a-table :columns="columnsa" :data-source="datavideo" :row-selection="rowSelection" /> -->
                <a-table :data="datavideo" row-key="id" size="small" :pagination="false"
                    v-model:selectedKeys="selectedKeys" :row-selection="rowSelection" :default-expanded-keys="[1]"
                    @select-all="selectedAll" @select="selectedID" :scroll="{
                        x: 900,
                        y: 700
                    }" :scrollbar="{
                        x: '120%',
                        y: '100%'
                    }">
                    <template #columns>
                        <a-table-column title="名称">
                            <template #cell="{ record }">
                                {{ record.title }}
                            </template>
                        </a-table-column>
                        <a-table-column title="IP">
                            <template #cell="{ record }">
                                {{ record.ip }}
                            </template>
                        </a-table-column>
                        <a-table-column title="ID">
                            <template #cell="{ record }">
                                {{ record.id }}
                            </template>
                        </a-table-column>
                    </template>
                </a-table>
            </div>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { Modal, Message } from "@arco-design/web-vue";
import { getUserInfoListAPI, addUserAPI, editUserAPI, deleteUserAPI, getUserVideoUrl } from "@/api/modules/user/index"
import { getvideoPlayUrl, getchannelstream, saveUserVideoUrl, deletUserVideoUrl } from "@/api/modules/video/index";

import { onMounted } from "vue";

const formData = reactive({
    form: {
        name: "",
    },
    paged: 1,
    pageSize: 10
});
const formData2 = reactive({
    form: {
        name: "",
    },
    paged: 1,
    pageSize: 10
});
const visible = ref(false)
const total = ref(0)
const tableData = ref([]);
const form = reactive({
    email: "",
    phone: "",
    name: "",
    type: undefined,
    password: "",
    id: ""
})

onMounted(() => {
    init();
});
async function init() {
    let obj = {
        paged: formData.paged,
        pageSize: formData.pageSize
    }
    let res = await getUserInfoListAPI(obj, formData.form);
    total.value = 0
    tableData.value = [];
    if (res.status == 2) {
        total.value = res.data.totalCount;
        tableData.value = res.data.data;
    }
}
const formRef = ref();
const onReset = () => {
    formRef.value.resetFields();
    init();
};

function changePage(page) {

    formData.paged = page;
    init()
}

function onSearch() {
    init();
}

function onAdd() {
    form.phone = ""
    form.email = ""
    form.name = ""
    form.type = undefined
    form.password = ""
    form.id = undefined
    visible.value = true
}

let user = {
    user_id: '',
}
async function getchannellist(id) {
    let obj = {
        paged: formData2.paged,
        pageSize: formData2.pageSize,
    }
    user.user_id = id
    let res = await getUserVideoUrl(obj, user);
    if (res.data && res.data.data) {
        selectedKeys.value = res.data.data.map(item => item.video_url_id);
    } else {
        selectedKeys.value = []
    }
    console.log(selectedKeys.value);

    // selectedKeys

    // total.value = 0
    // tableData.value = [];
    // if (res.status == 2) {
    //     total.value = res.data.totalCount;
    //     tableData.value = res.data.data;
    // }
}

function onEdit(val) {
    inittree()
    getchannellist(val.id)

    form.phone = val.phone
    form.email = val.email
    form.name = val.name
    form.type = val.type + ""
    form.password = val.password
    form.id = val.id

}

const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: false,
    onlyCurrent: false,
});
let selectedKeys = ref([]);//回显已经绑定选的id

let datavideo = []
async function selectedAll(a) {
    console.log(a);
}
async function selectedID(a, b, c) {
    console.log(a);
    console.log(b);
    let ids = await findParentIds(datavideo, c.id)
    console.log(ids);

    const isIN = selectedKeys.value.includes(c.id);
    let obj = {
        user_id: user.user_id,
        video_url_ids: ids
    }
    if (!isIN) {//包含 输出 true，否则输出 false
        let res = await deletUserVideoUrl(obj);
        if (res.status == 2) {
            Message.success("成功解除关联")
        } else {
            Message.error("解除关联失败")
        }
    } else {
        let res = await saveUserVideoUrl(obj);
        if (res.status == 2) {
            Message.success("关联成功")
        } else {
            Message.error("关联失败")
        }

    }

}

//传入id 一直往上查找父集id  传入3返回 [1,2,3]
async function findParentIds(data, targetId) {
    let result = [];

    function findNode(node) {

        if (node.id === targetId) {
            result.push(node.id);
            return true;
        }

        // 搜索子集（如果有的话
        if (node.children) {
            for (let child of node.children) {
                if (findNode(child)) {
                    result.unshift(node.id); //将当前节点的id添加到前面
                    return true;
                }
            }
        }

        return false;
    }

    for (let node of data) {
        if (findNode(node)) {
            break;
        }
    }

    return result;
}

async function inittree() {
    let res = await getvideoPlayUrl();
    if (res.status == 2) {
        datavideo = buildTree(res.data)
        visible.value = true
    }
}
// 构建树结构
function buildTree(data) {
    const map = new Map();
    const root = [];

    // 初始化所有节点
    data.forEach(item => {
        item.children = [];
        map.set(item.id, item);
    });

    // 按照 pid 来构建树
    data.forEach(item => {
        if (item.pid === 0) {
            root.push(item);
        } else {
            const parent = map.get(item.pid);
            if (parent) {
                parent.children.push(item);
            }
        }
    });

    // 清理没有子节点的 children 字段
    const cleanTree = (node) => {
        if (node.children && node.children.length === 0) {
            delete node.children; // 如果没有子节点，删除 children 字段
        } else if (node.children) {
            node.children.forEach(cleanTree); // 递归清理子节点
        }
    };

    // 遍历根节点，清理树
    root.forEach(cleanTree);
    return root;
}


const handleSubmit = async ({ values, errors }) => {
    console.log('values:', values, '\nerrors:', errors)
    if (errors) {
        return
    }
    if (form.id) {
        let res = await editUserAPI(values) as any
        if (res.status == 2) {
            Message.success("操作成功")
        } else {
            Message.error(res.statusMsg)
        }
    } else {
        let res = await addUserAPI(values) as any
        if (res.status == 2) {
            Message.success("操作成功")
        } else {
            Message.error(res.statusMsg)
        }
    }
    init();
    visible.value = false
}

const onDelete2 = (row: any) => {
    Modal.warning({
        title: "提示",
        content: "确定删除？",
        hideCancel: false,
        closable: true,
        onOk: async () => {
            try {
                let res = (await deleteUserAPI(row.id)) as any;
                if (res.status == 2) {
                    Message.success("删除成功");
                } else {
                    Message.error(res.statusMsg);
                }
                init();
            } catch { }
        }
    });
};
</script>

<style lang="scss" scoped></style>